package com.powerhua.privilege.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.powerhua.privilege.PrivilegeUtils;
import com.powerhua.privilege.domain.User;

public class PrivilegeFilter implements Filter {
	
	private ServletContext context;
	
	private String targetURI;
	
	public void init(FilterConfig filterConfig) throws ServletException {
		context = filterConfig.getServletContext();
		targetURI=filterConfig.getInitParameter("targetURI");
	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest)req;
		HttpSession session = httpRequest.getSession(true);
		if(session.getAttribute(PrivilegeUtils.SESSION_CURRENT_USER) != null) {
			
		} else {
			User user = new User();
			user.setUserId("2");
			List list = PrivilegeUtils.getUserManager().findUsers(user, 0, 0);
			if(list != null && list.size() > 0) {
				user = (User)list.get(0);
			}
			
			session.setAttribute(PrivilegeUtils.SESSION_CURRENT_USER, user);
		}
		chain.doFilter(req, res);
	}
	
	public void destroy() {
		context = null;
		targetURI = null;
	}

}
